import time
import network
import usocket as socket
import json

# Configuration
AP_SSID = 'ap_c3'
AP_IP = '192.168.4.1'
CONFIG_FILE = 'config.json'

def start_ap_mode():
    print('Starting Access Point mode...')
    
    # Deactivate station mode
    wlan_sta = network.WLAN(network.STA_IF)
    if wlan_sta.active():
        wlan_sta.active(False)
        print('Station mode deactivated sleep5')
        time.sleep(5)
    
    # Configure AP mode
    ap = network.WLAN(network.AP_IF)
    print('AP mode sleep5-->'+str(ap.active()))
    if ap.active():
        ap.active(False)
        print('AP mode deactivated sleep5')
        time.sleep(5)
    
    # ap = network.WLAN(network.AP_IF)
    # ap.config(essid=AP_SSID,password='12345678',authmode=network.AUTH_WPA_WPA2_PSK)
    # ap.active(True)

    print('[boot]_[ap_init] -->> Init AP mode with ssid :'+AP_SSID)
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid=AP_SSID, channel=11,security=0)
    ap.config(max_clients=5)
    ap.ifconfig((AP_IP, '255.255.255.0', AP_IP, '8.8.8.8'))
    return ap
    

def save_wifi_config(ssid, password):
    try:
        # Try to load existing config
        try:
            with open(CONFIG_FILE, 'r') as f:
                config = json.load(f)
        except:
            config = {}
        
        # Update WiFi config
        config['wifi'] = {
            'ssid': ssid,
            'password': password
        }
        
        # Save config
        with open(CONFIG_FILE, 'w') as f:
            json.dump(config, f)
        
        print('WiFi config saved:', ssid)
        return True
    except Exception as e:
        print('Error saving config:', e)
        return False

def handle_request(client):
    try:
        # Read request
        request = client.recv(1024).decode('utf-8')
        print('Received:', request[:50], '...' if len(request) > 50 else '')
        
        # Handle POST requests
        if request.startswith('POST'):
            # Find POST data
            data_start = request.find('\r\n\r\n') + 4
            post_data = request[data_start:]
            
            # Parse form data
            params = {}
            for param in post_data.split('&'):
                if '=' in param:
                    key, value = param.split('=', 1)
                    params[key] = value.replace('+', ' ')
            
            # Handle WiFi config
            if 'ssid' in params:
                ssid = params['ssid']
                password = params.get('password', '')
                
                if save_wifi_config(ssid, password):
                    response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
                    response += '<h1>Config Saved!</h1>'
                    response += '<p>WiFi SSID: ' + ssid + '</p>'
                    response += '<p>Device will restart on next power cycle.</p>'
                else:
                    response = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/html\r\n\r\n'
                    response += '<h1>Error Saving Config</h1>'
            else:
                response = 'HTTP/1.1 400 Bad Request\r\nContent-Type: text/html\r\n\r\n'
                response += '<h1>Bad Request</h1>'
        else:
            # Send config form for GET requests
            response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
            response += '<!DOCTYPE html><html><body>'
            response += '<h1>ESP32C3 WiFi Config</h1>'
            response += '<form method="post">'
            response += 'SSID: <input type="text" name="ssid" required><br>'
            response += 'Password: <input type="password" name="password"><br>'
            response += '<input type="submit" value="Save">'
            response += '</form>'
            response += '</body></html>'
        
        # Send response
        client.send(response.encode('utf-8'))
    except Exception as e:
        print('Error handling request:', e)
    finally:
        client.close()

def run_http_server():
    print('Starting HTTP server on port 80...')
    
    # Create socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((AP_IP, 80))
    s.listen(1)
    
    print('Server running at http://' + AP_IP + '/')
    print('Connect to WiFi: ' + AP_SSID)
    
    try:
        while True:
            # Accept connection
            conn, addr = s.accept()
            print('Client connected from:', addr)
            
            # Handle request in main thread (simplified)
            handle_request(conn)
            
    except Exception as e:
        print('Server error:', e)
    finally:
        s.close()

# Main program
if __name__ == '__main__':
    print('=== ESP32C3 AP Mode Test ===')
    print('No WiFi config found, starting AP mode...')
    
    # Start Access Point
    ap = start_ap_mode()
    
    # # Run HTTP server
    run_http_server()